package com.windy.dailynews.presenter.impl;

import android.util.Log;

import com.google.gson.Gson;
import com.windy.dailynews.model.News;
import com.windy.dailynews.presenter.HomeContract;
import com.windy.dailynews.request.DataRequest;

import org.json.JSONObject;

/**
 * Created by dingfeng on 2016/11/21.
 */
public class HomePresenter implements HomeContract.Presenter {

    private final HomeContract.View mView;
    private String newsDate;

    public HomePresenter(HomeContract.View view) {
        mView = view;
        mView.setPresenter(this);
    }

    @Override
    public void start() {
        loadData();
    }

    @Override
    public void loadData() {
        mView.setLoading();
        DataRequest.getInstance().getLatestNews(new DataRequest.Callback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject data) {
                if (data != null) {
                    Gson gson = new Gson();
                    News news = gson.fromJson(data.toString(), News.class);
                    newsDate = news.getDate();
                    mView.hideLoading();
                    mView.showTopAd(news.getTop_stories());
                    mView.showNewsList(news.getStories());
                } else {
                    mView.setError();
                }

            }

            @Override
            public void onError(String err) {
                mView.setError();
            }
        });
    }

    @Override
    public void loadMore() {
        DataRequest.getInstance().getBeforeNews(newsDate, new DataRequest.Callback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject data) {
                Gson gson = new Gson();
                News news = gson.fromJson(data.toString(), News.class);
                newsDate = news.getDate();
                mView.addBeforeList(news.getStories());
            }

            @Override
            public void onError(String err) {

            }
        });
    }

}
